/*
 * Created by SharpDevelop.
 * User: Oscar
 * Date: 29/09/2007
 * Time: 08:02 p.m.
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Web;
using System.Web.UI;
using System.Configuration;


namespace DemoPress.UrlRewriting
{
	/// <summary>
	/// Description of UrlRewriteModule.
	/// </summary>
	public class UrlRewriteModule : IHttpModule
	{
		public UrlRewriteModule()
		{
		}
		
		public void Init(HttpApplication context)
		{
			//register handlers
			context.BeginRequest += new EventHandler(OnBeginRequest);
			context.PreRequestHandlerExecute += new EventHandler(OnPreRequestHandlerExecute);
		}
		
		private void OnBeginRequest(object obj, EventArgs ea)
		{
			UrlRewriteSectionHandler handler = (UrlRewriteSectionHandler) ConfigurationManager.GetSection("modulesSection/urlRewriteModule");
			if(!handler.RewriteOn)
			{
				return;
			}
			string path = HttpContext.Current.Request.Path;
			if(String.IsNullOrEmpty(path))
			{
				return;
			}
			foreach (UrlRewriteRule rule in handler.Rules)
			{
				if(rule.MatchSource(path))
				{
					path = rule.RewritePath(path);
					if(!String.IsNullOrEmpty(path))
					{
						if(HttpContext.Current.Request.QueryString.Count > 0)
						{
							string sign = (path.IndexOf('?') == -1)? "?" : "&";
							path += sign + HttpContext.Current.Request.QueryString.ToString();
						}
						string newPath = handler.RewriteBase + path;
						HttpContext.Current.Items.Add("OriginalUrl", HttpContext.Current.Request.RawUrl);
						HttpContext.Current.RewritePath(newPath);
					}
					return;
				}
			}
		}
		
		private void OnPreRequestHandlerExecute(object obj, EventArgs ea)
		{
			HttpApplication app = (HttpApplication) obj;
			IHttpHandler handler = app.Context.CurrentHandler;
			if( (handler is Page) && (handler != null) )
			{
				Page page = (Page) handler;
				page.PreInit += new EventHandler(OnPagePreInit);
			}
		}
		
		private void OnPagePreInit(object obj, EventArgs ea)
		{
			if(HttpContext.Current.Items.Contains("OriginalUrl"))
			{
				string path = (string) HttpContext.Current.Items["OriginalUrl"];
				UrlRewriteContext context = new UrlRewriteContext(HttpContext.Current.Request.QueryString, path);
				HttpContext.Current.Items["UrlRewriteContext"] = context;
				if(path.IndexOf('?') == -1)
				{
					path += "?";
				}
				HttpContext.Current.RewritePath(path);
			}
		}
		
		public void Dispose()
		{
			throw new NotImplementedException();
		}
		
	}
}
